package com.hxzy.shop.controller.auth;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.hxzy.shop.cachedao.AuthCacheService;
import com.hxzy.shop.constant.AuthConstant;
import com.hxzy.shop.constant.ShopConstant;
import com.hxzy.shop.dto.auth.req.ActivateMerchantReq;
import com.hxzy.shop.dto.auth.req.CaptchaCodeReq;
import com.hxzy.shop.dto.auth.req.LoginReq;
import com.hxzy.shop.dto.auth.resp.LoginResp;
import com.hxzy.shop.dto.auth.resp.MerchantResp;
import com.hxzy.shop.dto.auth.resp.Oauth2TokenDto;
import com.hxzy.shop.feign.auth.AuthFeign;
import com.hxzy.shop.feign.merchant.MerchantFeign;
import com.hxzy.shop.utils.HttpHeadUtils;
import com.hxzy.shop.vo.ApiException;
import com.hxzy.shop.vo.Result;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName AuthController
 * @Author wengjt
 * @Date 2021/8/3 10:27
 * @Description
 **/
@RestController
@Api(tags = "登录授权接口")
@Slf4j
@RequestMapping("/auth")
public class AuthController {
 @Resource
    private AuthCacheService authCacheService;

    /**
     * auth的feign远程调用服务
     */
    @Autowired
    private AuthFeign authFeign;

    /**
     * merchant的feign远程调用服务
     */
    @Autowired
    private MerchantFeign merchantFeign;

    @GetMapping(value = "/rsa/publicKey")
    public Map<String, Object> getKey(){
        return authFeign.getKey();
    }

    /**
     * 获取验证码
     * @param captchaCodeReq
     * @return
     */
    @ApiOperation("验证码")
    @GetMapping("/captchaCode")
    public Result<Map<String,String>> captcha(CaptchaCodeReq captchaCodeReq){


        Captcha captcha=null;

        if(ShopConstant.PNG.equals( captchaCodeReq.getType())){
            captcha=new SpecCaptcha(captchaCodeReq.getWidth(), captchaCodeReq.getHeight());
        }else if(ShopConstant.GIF.equals(captchaCodeReq.getType())){
            captcha=new GifCaptcha(captchaCodeReq.getWidth(), captchaCodeReq.getHeight());
        }else{
            captcha= new ArithmeticCaptcha(captchaCodeReq.getWidth(),captchaCodeReq.getHeight());
        }
        captcha.setLen(captchaCodeReq.getCodeCount());
        //验证码的结果
        String value = captcha.text();
        //令牌
        String uuid= UUID.randomUUID().toString();
        //存放到redis中 "back:captcha:"+uuid
        String redisKey= uuid;

        //存入到redis，
        this.authCacheService.savaCaptchaCode(redisKey, value);

        //返回给前端
        Map<String,String> map=new HashMap<>(16);
        map.put("uuid",uuid);
        map.put("image", captcha.toBase64());
        return  Result.success(map);
    }

    /**
     * 会员登录
     *
     * @param req
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public Result<LoginResp> login(@RequestBody LoginReq req) {

        if (!authCacheService.checkCaptchaCode(req.getCaptchaNo(), req.getCaptchaCode())){
            throw new ApiException(500,"验证码错误");
        }
        HashMap<String,String> parameters =new HashMap<>();
        parameters.put("grant_type","password");
        parameters.put("client_id", AuthConstant.ADMIN_CLIENT_ID);
        parameters.put("client_secret",AuthConstant.ADMIN_CLIENT_SECRET);
        parameters.put("username",req.getAccount());
        parameters.put("password",req.getPassword());
        Result<Oauth2TokenDto> oauth2TokenDtoResult = this.authFeign.postAccessToken(parameters,null);
        if (oauth2TokenDtoResult.getCode()==200){
            LoginResp result=new LoginResp();
            result.setToken(oauth2TokenDtoResult.getData().getToken());
            return Result.success(result);
        }else {
            throw new ApiException(oauth2TokenDtoResult.getCode(),oauth2TokenDtoResult.getMsg());
        }
    }


    @ApiOperation("商户信息详情")
    @PostMapping("/merchantDetail")
    public Result<MerchantResp> getMerchantDetail(){
        return merchantFeign.getMerchantDetail();
    }


}
